import "../../../../scss/activity/collect/user_vote.scss";
import $ from "jquery";
import "../../../utils/weui";
import moment from "moment";
import "../../../utils/remove_ad";
import Vue from "vue";
import ps from "../../../common/vote_variable";
import ReadSection from "../../components/readSection";
import FuncBanner from "../../components/funcbanner";
import CtrlPlay from "../../components/ctrlplay";
import VoteuserJoin from "./voteUserJoin";
import com from "../../../utils/common";
import count from "../../../utils/countdown";
// import "../../../utils/cropper";
import "../../../utils/oldcommon/layer";
import wxtool from "../../components/weixin";
import SharePop from "../../components/sharePop";
import NoticePop from "../../components/noticeWay";
import viewAddFooter from "../../components/viewAddFooter";
import setWxShare from "../../components/setWxShare";

let user = wxtool.getWxUserinfo();
$(function() {
  let page = {
    _actid: com.getUrlParam("actid") ? com.getUrlParam("actid") : 1,
    _ispreview: com.getUrlParam("preview") ? com.getUrlParam("preview") : 0,
    _app: {},
    _appdata: {
      partinstatusall: ps, // 所有状态
      partinstatus: ps.ParterLook, //当前状态
      // 按票数排序
      RankList: [
          {
            Order: 1, // 排名
            JoinerId: 12, // joinerid
            Number: 44, // 编号 根据joinerid排名
            WorkImg: "/img/activity/collect/vote/test.jpg",
            WorksName: "紫色精灵",
            Votes: 27149,
            WorksDesc: "爱好摄影,15年开始自学,擅长静物摄影,喜欢从身边的事物发现美"
          }
        ],
        // 按编号排序
        NumberRank: [
          {
            Order: 123, // 排名
            Number: 12, // 编号 根据joinerid排名
            JoinerId: 11111, // joinerid 用于跳转
            WorkImg: "/img/activity/collect/vote/test.jpg",
            WorksName: "仰望星空",
            Votes: 999,
            WorksDesc: "爱好摄影,15年开始自学,擅长静物摄影,喜欢从身边的事物发现美"
          }
      ],
      // // 搜索结果
      SearchResult: [],
      countDown: {
        days: "xx",
        hours: "xx",
        minutes: "xx",
        seconds: "xx"
      }
    },

    _init: function() {
      // 获取活动数据
      let self = this;
      com.ajax({
        url: "/act/userVote/getActDetial",
        data: {
          Actid: self._actid,
          Openid: user.openid
        },
        ok: function(data) {
          let temp = data["msg"];
          console.log(data);
          if (temp !== "fail" && typeof temp === "object") {
            if (temp.Catgory == "collect/user_vote") {
              temp.Actid = self._actid;
              temp.Prizes = JSON.parse(temp.Prizes);
              temp.Other = JSON.parse(data["msg"]["Other"]);
              temp.StartDate = moment(temp.StartTime).format(
                "YYYY-MM-DD HH:mm"
              );
              temp.EndDate = moment(temp.EndTime).format("YYYY-MM-DD HH:mm");
              temp.Content = JSON.parse(temp.Content);
              console.log(temp);

              // 分享相关信息
              let ShareMsg = {};
              ShareMsg.ShareImg = temp.ShareImg;
              ShareMsg.ShareTitle = temp.ShareTitle
                ? temp.ShareTitle
                : temp.Title;
              ShareMsg.ShareContent = temp.ShareContent;
              self._appdata.ShareMsg = ShareMsg;

              /* 加载状态*/
              self._appdata.partinstatus = self._checkActStatus(data);
              console.log(self._appdata.partinstatus);
              let ActStatus = {};
              ActStatus.partinstatusall = ps;
              ActStatus.partinstatus = self._appdata.partinstatus;
              self._appdata.ActStatus = ActStatus;
              console.log(self._appdata);
              $.extend(self._appdata, temp);
              self._loadTemp();
            } else {
              com.alertDialog("类型错误");
            }
          } else {
            com.alertDialog("活动不存在");
          }
        }
      });
    },

    // 根据状态判断数据传输,页面交互
    _analysisStatus: function() {
      let self = this;
      if (self._ispreview) {
        $(".footer").hide();
        $(".preview-footer")
          .css("bottom", 0)
          .show();
        $(".preview-footer a:first-child").attr(
          "href",
          "/dist/activity/collect/user_vote_edit.html?actid=" + self._actid
        );
        $(".preview-footer a:last-child").attr(
          "href",
          "/dist/activity/collect/user_vote.html?actid=" + self._actid
        );
      }

      if (!self._ispreview) {
        // 没有人报名时的情况(大概率商家页)
        // 当是商家保存完活动打开页面后
        let checkEditUser = com.getdb(self._actid);
        console.log(checkEditUser);
        if (checkEditUser) {
          $(".share_mask").show();
          com.showCenter($(".share_pop"));
          com.savedb(self._actid, false);
        }
        let shareData = {
          ShareTitle: self._appdata.ShareMsg.ShareTitle,
          ShareImg: self._appdata.ShareMsg.ShareImg,
          ShareContent: self._appdata.ShareMsg.ShareContent,
          Actid: self._actid
        };
        setWxShare.SetShare(shareData);
      }
    },
    // 判断状态
    _checkActStatus: function(act) {
      console.log(act);
      let temp = act["msg"];
      let start = moment(temp.StartTime);
      let end = moment(temp.EndTime);
      let now = moment();

      //判断活动是否开始
      if (now.isBefore(start)) {
        return ps.AtActInActiveStart;
      }
      //判断活动是否开始
      if (now.isAfter(end)) {
        return ps.AtActInActiveEnd;
      }
      //判断用户是否参与过活动
      if (act.hasJoiner) {
        return ps.HasJoinerNow;
      } else {
        return ps.JoinJustNow;
      }
    },
    _loadTemp: function() {
      let self = this;

      console.log(self._appdata);
      Vue.component("read-section", ReadSection);
      Vue.component("func-banner", FuncBanner);
      Vue.component("music", CtrlPlay);
      Vue.component("notice-pop", NoticePop);
      Vue.component("share-pop", SharePop);
      Vue.component("voteuser-join", VoteuserJoin);
      Vue.component("add-msg", viewAddFooter);
      self._app = new Vue({
        el: "#app",
        data: self._appdata,
        methods: {
          // 显示弹窗,并让其显示在中间
          compare: function(property) {
            // 返回sort函数参数
            return function(obj1, obj2) {
              let value1 = obj1[property];
              let value2 = obj2[property];
              return value1 - value2; // 升序
            };
          },
          CastVote: function(RankArr, Number, index) {
            // 点击投票
            RankArr[index]["Votes"]++;
          },
          ShowWorkDetail: function(joinid) {
            window.location =
              "/dist/activity/collect/user_vote_page.html?actid=" +
              self._actid +
              "&joinid=" +
              joinid;
          },
          SearchWorks: function() {
            // 搜索投票信息
            // 参数
          },
          SearchJoiner: function() {
            com.ajax({});
          },
          AlertJoinPop: function() {
            let msg =
              '<p style="text-align:left;color:#333;">①报名前可先联系商家，确认活动真实性以及记录联系方式哦！<br/>②如发现虚假活动，请在客牛公众号回复我们。</p>';
            layer.open({
              content: msg,
              btn: ["确定", "取消"],
              yes: function() {
                layer.closeAll();
                $(".pop_mask").show();
                com.showCenter($(".pop_user_msg"));
              }
            });
          },
          // 提交报名信息
          UserJoinAct: function(data) {
            let JoinData = {};
            JoinData.Actid = self._actid;
            JoinData.Joinid = self._joinid;
            JoinData.ActivityCat = "collect/user_vote";
            JoinData.Name = data["Name"];
            JoinData.Mobile = data["Mobile"];
            JoinData.Other = data["Other"];
            JoinData.Results = data.JoinWorkImg;
            JoinData.Openid = user.openid;
            com.ajax({
              url: "/act/userVote/joinUserVote",
              method: "post",
              data: JoinData,
              ok: function(data) {
                console.log(data);
                if (data["msg"] == "ok") {
                  self._getJoinByOpenid();
                } else if (data["msg"] == "fail") {
                  com.alertDialog("同一活动不能重复报名");
                }
              }
            });
          },

          // 根据编号排名
          ByNumberRank: function() {
            com.ajax({
              url: "/act/userVote/getRankByNumber",
              data: {
                PageNum: 20,
                Actid: page._actid,
                PageSize: 1
              },
              ok: function(data) {
                let joiners = data["res"];
                for (let i = 0; i < joiners.length; ++i) {
                  self._app.NumberRank.push({
                    WorksName: joiners[i].WorkMsg.WorkName,
                    Votes: joiners[i].Current,
                    WorkImg: joiners[i].WorkImg,
                    JoinerId: joiners[i].JoinerId
                  });
                }
              }
            });
          },
          // 根据编号排名
          ByVoteRank: function() {
            com.ajax({
              url: "/act/userVote/getRankByVote",
              data: {
                PageNum: 20,
                Actid: page._actid,
                PageSize: 1
              },
              ok: function(data) {
                let joiners = data["res"];
                for (let i = 0; i < joiners.length; ++i) {
                  self._app.RankList.push({
                    WorksName: joiners[i].WorkMsg.WorkName,
                    Votes: joiners[i].Current,
                    WorkImg: joiners[i].WorkImg,
                    JoinerId: joiners[i].JoinerId
                  });
                }
              }
            });
          },
          // 返回自己页面
          BackMine: function() {
            self._getJoinByOpenid();
          }
        },
        updated: function() {}
      });
      self._analysisStatus();
      self._afterTemp();
    },
    _afterTemp: function() {
      let self = this;
      let main = {
        selectNav: function(btn, className, childClass) {
          btn.click(function() {
            let $index = $(this).index();
            $(this)
              .addClass(className)
              .siblings()
              .removeClass(className);
            if ($index < 2) {
              $(".rank_show_way").show();
              $(childClass)
                .eq($index)
                .show()
                .siblings()
                .hide();
            } else {
              $(".rank_show_way").hide();
            }
          });
        }
      };

      $("#app").on("click", ".mask,.cancel,.pop_mask,.close", function() {
        $(".mask,.pop_mask").hide();
      });
      $("#app").on(
        "click",
        ".share_pop,.pop_user_msg,.share-way,.sign-suc",
        function(event) {
          event.stopPropagation();
        }
      );

      main.selectNav($(".sort_order ul li"), "select", ".show_rules"); // 点击切换导航栏
      main.selectNav($("#rank_nav li"), "select", ".show_way"); // 点击切换导航栏
      // 倒计时
      let countDownTime = setInterval(function() {
        let timeRecord = count.computedTime(
          moment(self._app.EndDate).format("X")
        );
        if (timeRecord) {
          self._app.countDown = timeRecord;
        } else {
          self._app.partinstatus = self._app.partinstatusall.AtActInActiveEnd;
          clearInterval(countDownTime);
        }
      }, 1000);
    },
    _getJoinByOpenid: function() {
      let self = this;
      com.ajax({
        url: "/act/userVote/getJoinerDetail",
        data: {
          Openid: user.openid,
          Actid: self._actid
        },
        ok: function(dat) {
          console.log(dat);
          let joinMsg = dat["res"];
          if (joinMsg["Id"] > 0) {
            window.location =
              "/dist/activity/collect/user_vote_page.html?actid=" +
              self._actid +
              "&joinid=" +
              joinMsg["Id"];
          } else {
            com.alertDialog("您还未参加此活动");
          }
        }
      });
    }
  };
  page._init();
});
